package com.example.xymarket.adapter;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.xymarket.R;
import com.example.xymarket.po.ShoppingCart;
import com.example.xymarket.httpUtil.AsyncImageLoader;
import com.example.xymarket.httpUtil.CartService;
import com.example.xymarket.common.MyHandler;
import com.example.xymarket.common.MyUrl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CartAdapter extends BaseAdapter  {
    public List<ShoppingCart> items;
    Context context;
    int count = 0;
    int layout= 0;
    Handler ContextHandler =null;
    public HashMap<Integer, Drawable> hm;
    public CartAdapter(List<ShoppingCart> items, Context context,int layout,Handler handler) {
        super();
        this.items = items;
        this.context = context;
        this.layout=layout;
        count = items.size();
        hm=new HashMap<>();
        this.ContextHandler =handler;
    }

    @Override
    public int getCount() {
        return items.size();
    }

    @Override
    public Object getItem(int position) {
        return items.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @SuppressLint("SetTextI18n")
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ShoppingCart shoppingCart = items.get(position);
        String url = MyUrl.ImagesUrl + shoppingCart.getGoodsEntity().getImage();
        CartAdapter.MyViewHolder viewHolder = new CartAdapter.MyViewHolder();
        // 若无可重用的 view 则进行加载
        convertView = LayoutInflater.from(context).inflate(layout, null);
        // 初始化 MyViewHolder 方便重用
        viewHolder.id=shoppingCart.getId();
        viewHolder.goodsId=shoppingCart.getGoodsEntity().getId();
        viewHolder.name = (TextView) convertView.findViewById(R.id.order_name);
        viewHolder.name.setText(shoppingCart.getGoodsEntity().getTitle());
        viewHolder.sold = (TextView) convertView.findViewById(R.id.merchant_dis);
        viewHolder.sold.setText("月销："+String.valueOf(shoppingCart.getGoodsEntity().getSoldQty()));
        viewHolder.price = (TextView) convertView.findViewById(R.id.order_price);
        viewHolder.price.setText(String.valueOf(shoppingCart.getGoodsEntity().getPrice()/100)+"."
                +String.valueOf(shoppingCart.getGoodsEntity().getPrice()%100));
        viewHolder.imageView=(ImageView)convertView.findViewById(R.id.order_avatar);
        viewHolder.add=(Button) convertView.findViewById(R.id.add);
        viewHolder.num=(EditText) convertView.findViewById(R.id.buyNum);
        viewHolder.num.setText(String.valueOf(shoppingCart.getNum()));
        viewHolder.sub=(Button) convertView.findViewById(R.id.sub);
        viewHolder.checkBox=(CheckBox)convertView.findViewById(R.id.checkBox) ;
        viewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(viewHolder.checkBox.isChecked())
                {
                    Message message=new Message();
                    message.obj=shoppingCart;
                    message.what=2;
                    ContextHandler.sendMessage(message);
                }
                else
                {
                    Message message=new Message();
                    message.obj=shoppingCart;
                    message.what=-2;
                    ContextHandler.sendMessage(message);
                }
            }
        });
        viewHolder.add.setOnClickListener(new View.OnClickListener() {
                                              public void onClick(View v) {
                                                 add(viewHolder,shoppingCart);
                                              }
                                          });

        viewHolder.sub.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
               sub(viewHolder,shoppingCart);
            }
        });
        if(hm.get(position)!=null)
        {
            viewHolder.imageView.setImageDrawable(hm.get(position));
        }
        else
        {
            AsyncImageLoader asyncImageLoader = new AsyncImageLoader();
            asyncImageLoader.loadImage(url, viewHolder.imageView,hm,position);
        }
        convertView.setOnClickListener(new View.OnClickListener() {
                                           @Override
                                           public void onClick(View v) {
                                               Message message = new Message();
                                               message.obj = shoppingCart.getGoodsEntity().getId();
                                               message.what = 100;
                                               ContextHandler.sendMessage(message);
                                           }
                                       });
        convertView.setTag(viewHolder);
        return convertView;
    }


    @SuppressLint("HandlerLeak")
    final Handler handler = new Handler()
    {
        Map<String,Object> map = null;
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==2)
            {
                progressDialog = ProgressDialog.show(context,"","请稍等");
                map=(Map<String, Object>)msg.obj;
            }
            if(msg.what==3)
            {
                progressDialog = ProgressDialog.show(context,"","请稍等");
                map=(Map<String, Object>)msg.obj;
            }
            if(msg.what==1) {
                ShoppingCart shoppingCart=(ShoppingCart) map.get("shoppingCart");
                MyViewHolder viewHolder=(MyViewHolder) map.get("viewHolder");
                assert shoppingCart != null;
                shoppingCart.setNum((Integer) msg.obj);
                assert viewHolder != null;
                viewHolder.num.setText(String.valueOf(((Integer) msg.obj)));
                map.clear();
                progressDialog.dismiss();
            }
            if(msg.what==-1) {
                map.clear();
                progressDialog.dismiss();
            }
        }
    };

    private ProgressDialog progressDialog;

    public void add(MyViewHolder viewHolder,ShoppingCart shoppingCart) {
        Map<String,Object>map=new HashMap<>();
        map.put("shoppingCart",shoppingCart);
        map.put("viewHolder",viewHolder);
        Message message=new Message();
        message.obj=map;
        message.what=2;
        handler.sendMessage(message);
        MyHandler myHandler=new MyHandler(context,handler);
        CartService cartService=new CartService(myHandler);
        int num=Integer.parseInt(viewHolder.num.getText().toString())+1;
        cartService.InsertCart(viewHolder.id,viewHolder.goodsId,num);
    }

    public void sub(MyViewHolder viewHolder,ShoppingCart shoppingCart) {
        Map<String,Object>map=new HashMap<>();
        map.put("shoppingCart",shoppingCart);
        map.put("viewHolder",viewHolder);
        Message message=new Message();
        message.obj=map;
        message.what=3;
        handler.sendMessage(message);
        MyHandler myHandler=new MyHandler(context,handler);
        CartService cartService=new CartService(myHandler);
        int num=Integer.parseInt(viewHolder.num.getText().toString())-1;
        cartService.InsertCart(viewHolder.id,viewHolder.goodsId,num);
    }

    public final class MyViewHolder {
        int id;
        int goodsId;
        CheckBox checkBox;
        TextView name;
        TextView sold;
        TextView price;
        ImageView imageView;
        Button add;
        Button sub;
        EditText num;
    }
}
